package com.learnspringcloud.order.message;

import com.learnspringcloud.order.utils.JsonUtil;
import com.learnspringcloud.productcommon.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.Strings;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author Lin
 * @date 2018/11/23 0023
 */
@Component
@Slf4j
public class ProductInfoReceiver {

    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String message) {

        ProductInfoOutput output = (ProductInfoOutput) JsonUtil.fromJson(message, ProductInfoOutput.class);

        log.info("从队列: {}, 接收到消息: {}", "productInfo", output);

        // 存入到Redis中
        stringRedisTemplate.opsForValue().set(
                String.format(PRODUCT_STOCK_TEMPLATE, output.getProductId()),
                String.valueOf(output.getProductStock())
        );
    }
}
